import { _decorator, Component, Label, Node, Sprite, v3 } from 'cc';
import { Task, TaskStatus } from '../entity/Task';
import { Bonus } from '../entity/Bonus';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { GetBonus } from './GetBonus';
import TaskApi from '../api/TaskApi';
import { UserInfo } from '../common/UserInfo';
import { EventManager } from '../event/EventManager';
const { ccclass, property } = _decorator;

@ccclass('MainTaskItem')
export class MainTaskItem extends Component {

    @property(Sprite)
    cover:Sprite
    @property(Label)
    desc:Label
    @property(Node)
    receive:Node
    @property(Label)
    num:Label

    private task:Task

    start() {
        this.receive.on(Node.EventType.TOUCH_END, this.onReceive, this)
        this.node.on(Node.EventType.TOUCH_END, this.onClick, this)
    }

    async setData(task:Task){
        this.task = task

        this.desc.string = task.name

        if(task.status == TaskStatus.Complete){
            this.num.node.active = false
            this.receive.position = v3(this.receive.position.x, 0, 0)
        } else {
            this.receive.active = false
            this.num.string = task.statusStr
        }

        this.cover.spriteFrame = await task.getTaskImg()
    }

    async onReceive(){
        await UIManager.instance.showLoading()
        let res = await TaskApi.getBonus(this.task.id)
        UIManager.instance.closeLoading()
        console.log(res)
        let list = Bonus.getBonusObj(res.data)
        let ui = await UIManager.instance.openUI(PrefabEnum.GetBonus)
        ui.getComponent(GetBonus).setData(list)

        this.node.removeFromParent()
        UserInfo.instance.refreshVillageDetail()

        EventManager.instance.emit(EventManager.EventType.ReceiveTaskBonus, 1)
    }

    async onClick(){

        return

        let list = Bonus.getBonusObj(this.task.bonus)
        let ui = await UIManager.instance.openUI(PrefabEnum.GetBonus)
        ui.getComponent(GetBonus).setData(list)
        console.log(list)
    }
}


